import Vue from 'vue'
import Vuex from 'vuex'
import {signIn} from '../util/requestAll/user'
import {selectMessageBySidOrRid} from '../util/requestAll/message'
import {setCookie} from '../util/cookieUtil'

Vue.use(Vuex)

const store = new Vuex.Store({
  state:{//获取get值：this.$store.state.webSocket
    /*
		* let webSocket = new WebSocket("ws://localhost:8888/websocket");
		*	webSocket.readyState：
		*		CONNECTING==0（正在连接）
		*		OPEN==1（连接成功，可以通信了）
		*		CLOSING==2（连接正在关闭）
		*		CLOSED==3（连接已经关闭，或者打开连接失败）
		*/
    webSocket:{readyState:3}, //websocket连接
    hallMessage:[],//大厅消息
    groupMessage:[],//群消息
    singleMessage:[],//个人消息
  },
  getters:{//获取get值：this.$store.getters.getWebSocket
    getWebSocket:state => {return state.webSocket},//websocket连接
    getWebSocketReadyState:state => {return state.webSocket.readyState},//websocket状态
    getHallMessage:state => {return state.hallMessage},//大厅消息
    getGroupMessage:state => {return state.groupMessage},//群消息
    getSingleMessage:state => {return state.singleMessage},//个人消息
  },
  mutations:{//改变set值：this.$store.commit("setWebSocket", value);
    setWebSocket(state,value){ state.webSocket = value; },
    setHallMessage(state,value){ state.hallMessage = value; },
    pushHallMessage(state,value){ state.hallMessage.push(value); },
    pushGroupMessage(state,value){ state.groupMessage.push(value); },
    pushSingleMessage(state,value){ state.singleMessage.push(value); },
  },
  actions: {//this.$store.dispatch('connectWebSocket',Object)//异步操作必须使用action调用
    connectWebSocket (context,xxx) {
      let userId=context.state.userInfo.id
      if(userId==-1){
        alert('会话有问题，按f5刷新页面')
        return
      }
      let socket = new WebSocket("ws://10.76.16.49:8888/websocket/"+userId);
      /* 连接关闭后的回调函数 */
      socket.onclose = event => {
        console.log("连接关闭后的回调函数：");
        console.log(event);
      };
      /* 报错时的回调函数 */
      socket.onerror = event => {
        console.log("报错时的回调函数：");
        console.log(event);
      };
      /* 收到服务器数据后的回调函数 */
      socket.onmessage = event => {
        // console.log("收到服务器数据后的回调函数：");
        let data=JSON.parse(event.data)
        // console.log(data);
        if(data.receive_type=='HALL'){
          context.commit('pushHallMessage',data)
        }else if(data.receive_type=='GROUP'){
          context.commit('pushGroupMessage',data)
        }else if(data.receive_type=='SINGLE'){
          context.commit('pushSingleMessage',data)
        }
      };
      return new Promise((resolve, reject) => {
        socket.onopen = event => {
          // console.log("连接成功后的回调函数执行：");
          // console.log(socket.readyState)
          //通过commit提交一个名为setWebSocket的mutation
          context.commit('setWebSocket',socket)
          resolve(socket);
        };
      })
    },
    getHallMessage(context,xxx){
      let userId=context.state.userInfo.id
      if(userId==-1){
        alert('会话有问题，按f5刷新页面')
        return
      }
      let data={
        // send_user_id:userId,//发送者id
        receive_type:'HALL',//'GROUP'、'SINGLE'、'HALL'（群聊、单聊、大厅）
        // receive_user_id:userId//发送给谁（SINGLE单聊必填）
      }
      return new Promise((resolve, reject) => {
        selectMessageBySidOrRid(data).then(res=>{
          let resData=res.data
          // console.log(resData)
          context.commit('setHallMessage',resData)
          resolve(resData);
        }).catch(err=>{
          reject(err);
        })
      })
    }
  },
  modules:{
    userInfo:{
      state:{//获取get值：this.$store.state.userInfo.id
        id:-1,
        username:'',
        passward:'',
        phone:'',
        email:'',
        nickname:''
      },
      mutations:{//不能和上面重复名字，调用this.$store.commit('setId',value)
        setId:(state,value)=>{ state.id = value; },
        setUserName:(state,value)=>{ state.username = value; },
        setPassWard:(state,value)=>{ state.passward = value; },
        setPhone:(state,value)=>{ state.phone = value; },
        setEmail:(state,value)=>{ state.email = value; },
        setNickName:(state,value)=>{ state.nickname = value; }
      },
      getters:{//不能和上面重复名字，调用this.$store.getters.getId
        getId:(state,getters,rootstate) => { return state.id; },
        getUserName:(state,getters,rootstate)=>{ return state.username; },
        getPassWard:(state,getters,rootstate)=>{ return state.passward; },
        getPhone:(state,getters,rootstate)=>{ return state.phone; },
        getEmail:(state,getters,rootstate)=>{ return state.email; },
        getNickName:(state,getters,rootstate)=>{ return state.nickname; }
      },
      actions: {//不能和上面重复名字，this.$store.dispatch('setLoginByEmailAndPwd',Object)//异步操作必须使用action调用
        loginByEmailAndPwd (context,data) {
          return new Promise((resolve, reject) => {
            signIn(data).then(res=>{
              let resData=res.data
              if(resData.resStatus==1){//登陸成功
                context.commit('setId',resData.id)
                context.commit('setUserName',resData.username)
                context.commit('setPassWard',resData.passward)
                context.commit('setPhone',resData.phone)
                context.commit('setEmail',resData.email)
                context.commit('setNickName',resData.nickname)
                setCookie("token",resData.sessionId)
              }
              resolve(resData);
            }).catch(err=>{
              reject(err);
            })
          })
        }
      }
    }
  }
})

export default store
